package com.tm.controller;

import com.tm.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author huangp
 * @create 2023-04-03 16:42
 */
@RestController
@RequestMapping("/common")
@CrossOrigin
public class CommonController {

   @Value("${file.path}")
    private String path;

   @PostMapping("download")
     public Result upload(@RequestBody MultipartFile file){
         //获取原始文件名称
         String originalFilename = file.getOriginalFilename();
         //截取文件后缀名的起始下标
         int i = originalFilename.lastIndexOf(".");
         //文件后缀
         String suffix = originalFilename.substring(i);
         String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;
         File newFile = new File(path);
         //判断这个文件夹是否存在
         if(newFile.exists()){
             newFile.mkdir();
         }
         File newFile2 = new File(path, newFileName);
         try {
             file.transferTo(newFile2);
         } catch (IOException e) {
             e.printStackTrace();
         }

         return Result.success(newFileName);
     }

}
